<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from '@/utils/axios.ts'
import { useRouter, useRoute } from 'vue-router'
import { showSuccessToast, showFailToast, showDialog } from 'vant'

// 获取路由实例
const router = useRouter()
const route = useRoute()

// 游戏详情数据
const gameInfo = ref({
  gameId: '',
  gameName: '',
  platform: '',
  type: '',
  intro: '',
  score: 0,
  coverImage: '',
})

// 轮播图图片数组
const gameImages = ref([])

// 按钮状态
const isAdding = ref(false)
const isAdded = ref(false)

// 获取游戏详情
const fetchGameDetail = () => {
  const gameId = route.params.id

  if (!gameId) {
    console.warn('游戏ID无效')
    return
  }

  // 使用正确的接口路径
  axios.post(`/api/games/detail?id=${gameId}`)
      .then(res => {
        gameInfo.value = res.data
        // 设置轮播图图片（假设返回多个图片）
        gameImages.value = [res.data.coverImage]
        // 检查游戏是否已关注
        checkIfAdded()
      })
      .catch(err => {
        console.error('获取游戏详情失败:', err)
      })
}

// 检查游戏是否已关注
const checkIfAdded = () => {
  const token = localStorage.getItem('token')
  if (!token) {
    isAdded.value = false
    return
  }

  // 确保请求头中包含token
  const config = {
    headers: {
      'token': token
    }
  }

  axios.get(`/api/userGames/checkGame?gameId=${gameInfo.value.gameId}`, config)
      .then(res => {
        if (res.code === 200) {
          isAdded.value = res.data.isAdded
        }
      })
      .catch(err => {
        console.error('检查游戏是否已关注失败:', err)
      })
}

// 返回上一页
const goBack = () => {
  try {
    // 检查 router 是否存在且有 back 方法
    if (router && typeof router.back === 'function') {
      // 检查浏览器历史记录
      if (typeof window !== 'undefined' && window.history.length > 1) {
        router.back()
      } else {
        // 如果无法返回，则跳转到游戏库页面
        router.push('/gameLibrary')
      }
    } else {
      // router 或 back 方法不存在时的备选方案
      if (typeof window !== 'undefined') {
        window.history.back()
      } else {
        // 最后的备选方案，直接跳转到游戏库
        window.location.href = '/gameLibrary'
      }
    }
  } catch (error) {
    console.error('返回操作出错:', error)
    // 出错时的最终备选方案
    if (typeof window !== 'undefined') {
      window.location.href = '/gameLibrary'
    }
  }
}

// 关注游戏
const followGame = () => {
  const token = localStorage.getItem('token')
  if (!token) {
    showDialog({
      title: '提示',
      message: '请先登录后再关注游戏',
      confirmButtonText: '去登录',
      cancelButtonText: '取消',
      showCancelButton: true
    }).then(() => {
      // 确认按钮回调，跳转到登录页
      router.push('/login')
    }).catch(() => {
      // 取消按钮回调
      console.log('用户取消登录')
    })
    return
  }

  // 设置按钮为加载状态
  isAdding.value = true

  // 确保请求头中包含token
  const config = {
    headers: {
      'token': token,
      'Content-Type': 'application/json'
    }
  }

  // 调用后端API关注游戏
  axios.post(`/api/userGames/addUserGame`, { gameId: gameInfo.value.gameId }, config)
      .then(res => {
        if (res.code === 200) {
          showSuccessToast('已关注游戏')
          isAdded.value = true
        } else {
          showFailToast('关注失败: ' + res.msg)
        }
      })
      .catch(err => {
        console.error('关注游戏失败:', err)
        showFailToast('关注失败，请重试')
      })
      .finally(() => {
        // 重置按钮加载状态
        isAdding.value = false
      })
}

// 页面挂载时加载数据
onMounted(() => {
  fetchGameDetail()
})
</script>

<template>
  <div class="game-detail-page">
    <!-- 返回按钮 -->
    <div class="back-button" @click="goBack">
      <van-icon name="arrow-left" size="20" color="#333" />
      <span>返回</span>
    </div>

    <!-- 轮播图 -->
    <van-swipe class="game-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item v-for="(image, index) in gameImages" :key="index">
        <img :src="image" class="game-image" />
      </van-swipe-item>
    </van-swipe>

    <!-- 游戏基本信息 -->
    <div class="game-info">
      <div class="title-section">
        <h2 class="game-title">{{ gameInfo.gameName }}</h2>
        <p class="platform">{{ gameInfo.platform }}</p>
        <p class="type">{{ gameInfo.type }}</p>
      </div>

      <!-- 简介 -->
      <div class="description">
        <h3>简介</h3>
        <div class="intro">
          <p>{{ gameInfo.intro }}</p>
        </div>
      </div>
      
      <!-- 关注游戏按钮 -->
      <div class="actions">
        <van-button 
          type="primary" 
          block 
          :loading="isAdding"
          :disabled="isAdded"
          @click="followGame">
          {{ isAdded ? '已关注' : '关注游戏' }}
        </van-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.game-detail-page {
  padding: 16px;
  max-width: 800px;
  margin: 0 auto;
  background-color: #f7f8fa;
}

.game-swipe {
  height: 250px;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 16px;
}

.game-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.game-info {
  background: white;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.title-section {
  margin-bottom: 16px;
}

.game-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
  line-height: 1.4;
}

.platform, .type {
  font-size: 14px;
  color: #666;
  margin: 4px 0;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  cursor: pointer;
  color: #333;
  font-size: 16px;
  text-decoration: none;
}

.back-button:hover {
  color: #666;
}

.actions {
  margin-top: 20px;
}
</style>